<template>
  <!-- 资产组成部位表单弹窗 -->
  <div>
    <el-dialog
      :close-on-click-modal="false"
      v-model="visibleDialog"
      :title="props.title"
      :width="!props.isReadonly ? '600px' : '750px'"
      draggable
      @close="closeDialog"
    >
      <el-form
        v-show="!props.isReadonly"
        ref="formRef"
        :model="formData"
        :rules="rules"
        label-width="120px"
      >
        <el-row>
          <el-col :span="24">
            <el-form-item label="设备种类" prop="assetTypeId">
              <el-tree-select
                v-if="!props.isReadonly"
                placeholder="请选择设备种类"
                v-model="formData.assetTypeId"
                :data="catalogList"
                node-key="id"
                :props="{
                  label: 'assetTypeName',
                  value: 'id',
                  children: 'nodes',
                }"
                :disabled="props.assetTypeId !== ''"
                :render-after-expand="false"
                :check-strictly="true"
                style="width: 100%"
                clearable
                @change="changeEquipType"
              />
            </el-form-item>
          </el-col>
          <el-col :span="24">
            <el-form-item label="设备" prop="assetName">
              <el-input
                :disabled="!formData.assetTypeId || props.assetTypeId !== ''"
                v-model="formData.assetName"
                placeholder="请选择设备"
                @focus="openSelectDialog()"
              />
            </el-form-item>
          </el-col>
          <el-col :span="24">
            <el-form-item label="部位编号" prop="positionCode">
              <el-input
                v-model="formData.positionCode"
                placeholder="请输入部位编号"
                clearable
              />
            </el-form-item>
          </el-col>

          <el-col :span="24">
            <el-form-item label="部位名称" prop="positionName">
              <el-input
                v-model="formData.positionName"
                placeholder="请输入部位名称"
                clearable
              />
            </el-form-item>
          </el-col>
          <el-col :span="24">
            <el-form-item label="序号" prop="sort">
              <el-input
                v-model="formData.sort"
                placeholder="请输入序号"
                clearable
              />
            </el-form-item>
          </el-col>
          <el-col :span="24">
            <el-form-item label="启用状态" prop="enabled">
              <el-radio-group v-model="formData.enabled">
                <el-radio :label="1">启用</el-radio>
                <el-radio :label="0">停用</el-radio>
              </el-radio-group>
            </el-form-item>
          </el-col>
          <el-col :span="24">
            <el-form-item label="备注" prop="remarks">
              <el-input
                v-model="formData.remarks"
                placeholder="请输入备注"
                clearable
              />
            </el-form-item>
          </el-col>
        </el-row>
      </el-form>

      <el-descriptions
        v-show="props.isReadonly"
        class="margin-top"
        :column="2"
        size="large"
        border
      >
        <el-descriptions-item :span="2">
          <template #label>
            <div class="cell-item">设备种类</div>
          </template>
          <div style="width: 100%; word-break: break-all">
            {{ formData.assetTypeName }}
          </div>
        </el-descriptions-item>
        <el-descriptions-item>
          <template #label>
            <div class="cell-item">设备名称</div>
          </template>
          <div style="width: 100%; word-break: break-all">
            {{ formData.assetName }}
          </div>
        </el-descriptions-item>
        <el-descriptions-item>
          <template #label>
            <div class="cell-item">设备编码</div>
          </template>
          <div style="width: 100%; word-break: break-all">
            {{ formData.assetCode }}
          </div>
        </el-descriptions-item>
        <el-descriptions-item>
          <template #label>
            <div class="cell-item">部位编号</div>
          </template>

          <div style="width: 100%; word-break: break-all">
            {{ formData.positionCode }}
          </div>
        </el-descriptions-item>
        <el-descriptions-item>
          <template #label>
            <div class="cell-item">部位名称</div>
          </template>

          <div style="width: 100%; word-break: break-all">
            {{ formData.positionName }}
          </div>
        </el-descriptions-item>
        <el-descriptions-item>
          <template #label>
            <div class="cell-item">排序</div>
          </template>
          {{ formData.sort }}
        </el-descriptions-item>
        <el-descriptions-item>
          <template #label>
            <div class="cell-item">是否启用</div>
          </template>
          <el-tag v-show="formData.enabled === 1" type="">启用</el-tag>
          <el-tag v-show="formData.enabled !== 1" type="info">停用</el-tag>
        </el-descriptions-item>

        <el-descriptions-item>
          <template #label>
            <div class="cell-item">创建时间</div>
          </template>
          {{ formData.createTime }}
        </el-descriptions-item>
        <el-descriptions-item>
          <template #label>
            <div class="cell-item">创建人</div>
          </template>
          {{ formData.createdUserName }}
        </el-descriptions-item>
        <el-descriptions-item>
          <template #label>
            <div class="cell-item">更新时间</div>
          </template>
          {{ formData.lastUpdateTime }}
        </el-descriptions-item>
        <el-descriptions-item>
          <template #label>
            <div class="cell-item">更新人</div>
          </template>
          {{ formData.lastUpdatedUserName }}
        </el-descriptions-item>
        <el-descriptions-item :span="2">
          <template #label>
            <div class="cell-item">备注</div>
          </template>
          <div style="width: 100%; word-break: break-all">
            {{ formData.remarks || "暂无备注" }}
          </div>
        </el-descriptions-item>
      </el-descriptions>
      <template #footer>
        <div class="dialog-footer">
          <el-button
            v-if="!props.isReadonly"
            type="primary"
            :loading="loading"
            @click="handleSubmit"
            >确 定</el-button
          >
          <el-button @click="closeDialog">取 消</el-button>
        </div>
      </template>
    </el-dialog>
    <SelectDeviceDialog-Eam
      v-model:visible="selectDialog.visible"
      :data="selectDialog.data"
      :assetTypeId="formData.assetTypeId"
      :isMultiple="false"
      @echo-info="changeVisible"
    />
  </div>
</template>

<script setup lang="ts">
import request from "@/utils/request";
import { useDictStoreHook } from "@/store/modules/dictionary"; // 引入
const dictionaryStore = useDictStoreHook();

defineOptions({
  name: "EAMEAMASSETPOSITIONADDORUPDATE",
  inheritAttrs: false,
});

const emit = defineEmits(["reset-table", "change-visible"]);

const props = defineProps({
  visible: {
    type: Boolean,
    default: () => {
      return false;
    },
  },
  title: {
    type: String,
    default: () => {
      return "";
    },
  },
  data: {
    type: Object,
    default: () => {
      return {};
    },
  },
  isReadonly: {
    type: Boolean,
    default: () => {
      return false;
    },
  },
  parentId: {
    type: String,
    default: () => {
      return "";
    },
  },
  assetTypeId: {
    type: String,
    default: () => {
      return "";
    },
  },
  assetKind: {
    type: Number,
    default: 1,
  },
});

//  点击设备
function openSelectDialog() {
  selectDialog.visible = true;
  selectDialog.data = formData.assetId
    ? [
        {
          id: formData.assetId,
          assetName: formData.assetName,
          assetCode: formData.assetCode,
        },
      ]
    : [];
}
//设备显隐
const selectDialog = reactive<DialogOption>({
  visible: false,
  data: [],
});
// 设备选择确认后的回调函数
const changeVisible = (options: any) => {
  if (options && options.length) {
    const data = options[0];
    formData.assetId = data.id;
    formData.assetCode = data.assetCode;
    formData.assetName = data.assetName;
  } else {
    formData.assetId = "";
    formData.assetCode = "";
    formData.assetName = "";
  }
};

function changeEquipType() {
  formData.assetId = "";
  formData.assetCode = "";
  formData.assetName = "";
}

const subAdd = ref(false);

const visibleDialog = ref(false);
watch(
  () => props.visible,
  (newVal: boolean) => {
    visibleDialog.value = newVal;
    setTimeout(() => {
      formRef.value.clearValidate();
    }, 50);
  }
);

function validateDegree(rule: any, value: any, callback: (a?: any) => {}) {
  if (isNaN(parseFloat(value)) && isFinite(value)) {
    callback(new Error("请输入整数"));
  } else if (!/^[+-]?\d+?(e[+-]?\d+)?$/.test(value)) {
    callback(new Error("请输入整数"));
  } else if (Number(value) < 0) {
    callback(new Error("请输入大于0的整数"));
  } else {
    callback();
  }
}
const rules = reactive({
  assetTypeId: [
    { required: true, message: "请选择设备种类", trigger: "blur" },
    { min: 1, max: 32, message: "长度在 1 到 32 个字符", trigger: "blur" },
  ],
  positionCode: [
    { required: true, message: "请输入部位编号", trigger: "blur" },
    { min: 1, max: 20, message: "长度在 1 到 20 个字符", trigger: "blur" },
  ],
  positionName: [
    { required: true, message: "请输入部位名称", trigger: "blur" },
    { min: 1, max: 50, message: "长度在 1 到 50 个字符", trigger: "blur" },
  ],
  sort: [
    { required: true, message: "请输入序号", trigger: "blur" },
    { min: 1, max: 32, message: "长度在 1 到 32 个字符", trigger: "blur" },
    {
      validator: validateDegree,
      trigger: "blur",
    },
  ],
  remarks: [
    { min: 1, max: 255, message: "长度在 1 到 255 个字符", trigger: "blur" },
  ],
});

const formRef = ref(ElForm);

let formData = reactive({
  id: "",
  version: "",
  assetKind: "",
  assetTypeId: "",
  assetTypeName: "",
  assetBrandId: "",
  assetModelId: "",
  assetModelNo: "",
  positionCode: "",
  positionName: "",
  sort: "",
  parentId: "",
  allId: "",
  allCode: "",
  allName: "",
  remarks: "",
  createTime: "",
  createdUserId: "",
  createdUserName: "",
  lastUpdateTime: "",
  lastUpdatedUserId: "",
  lastUpdatedUserName: "",
  enabled: 1,
  deleted: "",
  // 设备信息
  assetId: "",
  assetName: "",
  assetCode: "",
});

watch(
  () => props.data,
  (newVal: any) => {
    formData.id = "";
    if (newVal?.id) {
      const {
        id,
        version,
        assetKind,
        assetTypeId,
        assetTypeName,
        assetBrandId,
        assetModelId,
        assetModelNo,
        positionCode,
        positionName,
        sort,
        parentId,
        allId,
        allCode,
        allName,
        remarks,
        createTime,
        createdUserId,
        createdUserName,
        lastUpdateTime,
        lastUpdatedUserId,
        lastUpdatedUserName,
        enabled,
        deleted,
        // 设备信息
        assetId,
        assetName,
        assetCode,
      } = newVal;
      Object.assign(formData, {
        id,
        version,
        assetKind,
        assetTypeId,
        assetTypeName,
        assetBrandId,
        assetModelId,
        assetModelNo,
        positionCode,
        positionName,
        sort,
        parentId,
        allId,
        allCode,
        allName,
        remarks,
        createTime,
        createdUserId,
        createdUserName,
        lastUpdateTime,
        lastUpdatedUserId,
        lastUpdatedUserName,
        enabled,
        deleted,
        // 设备信息
        assetId,
        assetName,
        assetCode,
      });
    }
  }
);

/** 关闭表单弹窗 */
function closeDialog() {
  visibleDialog.value = false;
  emit("change-visible", false);
  resetForm();
}

/** 重置表单 */
function resetForm() {
  formRef.value.resetFields();
  formRef.value.clearValidate();
  formData.id = "";
  formData.version = "";
  formData.assetKind = "";
  formData.assetTypeId = "";
  formData.assetTypeName = "";
  formData.assetBrandId = "";
  formData.assetModelId = "";
  formData.assetModelNo = "";
  formData.positionCode = "";
  formData.positionName = "";
  formData.sort = "";
  formData.parentId = "";
  formData.allId = "";
  formData.allCode = "";
  formData.allName = "";
  formData.remarks = "";
  formData.createTime = "";
  formData.createdUserId = "";
  formData.createdUserName = "";
  formData.lastUpdateTime = "";
  formData.lastUpdatedUserId = "";
  formData.lastUpdatedUserName = "";
  formData.enabled = 1;
  formData.deleted = "";
  formData.assetId = "";
  formData.assetName = "";
  formData.assetCode = "";
  subAdd.value = false;
}

const loading = ref(false);

const parentIdDialog = ref("");
watch(
  () => props.parentId,
  (newVal: string) => {
    parentIdDialog.value = newVal;
  }
);
watch(
  () => props.assetTypeId,
  (newVal: string) => {
    formData.assetTypeId = newVal;
    formData.assetCode = props.data.assetCode || "";
    formData.assetName = props.data.assetName || "";
    formData.assetId = props.data.assetId || "";
  }
);
/** 资产组成部位保存提交 */
function handleSubmit() {
  formRef.value.validate(async (valid: any) => {
    if (valid) {
      loading.value = true;
      // 添加子机构
      const text = ref("");
      if (parentIdDialog.value) {
        formData.parentId = parentIdDialog.value;
        loading.value = true;
        text.value = "添加资产组成子部位";
      } else if (formData.id) {
        loading.value = true;
        text.value = "编辑";
      } else {
        loading.value = true;
        formData.parentId = "0";
        text.value = "新增";
      }
      formData.assetKind = props.assetKind;
      await request({
        url: "/eam/eamassetposition/save",
        method: "post",
        data: formData,
      }).finally(() => {
        loading.value = false;
      });
      ElMessage.success(text.value + `成功`);
      closeDialog();
      emit("reset-table", formData.id);
    }
  });
}

// 组件销毁时调用
onBeforeUnmount(() => {
  visibleDialog.value = false;
  emit("change-visible", false);
});

// 目录树
const catalogList: any = ref([]);

// 获取内容树数据
const getCAtalogList = async () => {
  // 获取内容树
  await request({
    url: "eam/equAssetType/getAvailableTree",
    method: "POST",
    data: {},
  }).then((res) => {
    catalogList.value = res.data;
  });
};

onMounted(() => {
  getCAtalogList();
});
</script>
